package com.sec.etech.employeesync.util;

import com.alibaba.fastjson.JSONObject;
import com.sec.etech.employeesync.entity.OrgEmployee;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Slf4j
public class EmployeeDataConverter {

    @Autowired
    private ConfigTableHandlerFactory configTableHandlerFactory;

    public OrgEmployee convertToOrgEmployee(JSONObject employeeData) {
        OrgEmployee employee = new OrgEmployee();

        // 工号
        String account = StringUtils.trimToNull(employeeData.getString("PERNR"));
        if (StringUtils.isNotBlank(account)) {
            employee.setAccount(account);
        }

        // 姓名
        String sname = StringUtils.trimToNull(employeeData.getString("SNAME"));
        if (StringUtils.isNotBlank(sname)) {
            employee.setFullname(sname.replaceAll("\\s+", ""));
        }
        // 性别
        String gesch = StringUtils.trimToNull(employeeData.getString("GESCH"));
        if (StringUtils.isNotBlank(gesch)) {
            employee.setSex("1".equals(gesch) ? 1 : 0);
        }

        // 民族
        String zminzu = StringUtils.trimToNull(employeeData.getString("ZMINZU"));
        if (StringUtils.isNotBlank(zminzu)) {
            Long ethnicityId = getConfigId("ethnicity", zminzu);
            employee.setEthnicityId(ethnicityId);
        }

        // 出生日期
        employee.setBirthDate(parseDate(StringUtils.trimToNull(employeeData.getString("GBDAT"))));

        // 年龄
        employee.setAge(employeeData.getIntValue("AGE"));

        // 国籍
        String nationalityCode = StringUtils.trimToNull(employeeData.getString("NATIO"));
        String zhrhometown = StringUtils.trimToNull(employeeData.getString("ZHRHOMETOWN"));
        if (StringUtils.isNotBlank(nationalityCode)) {
            Long nationalityId = getConfigId("nationality", nationalityCode, zhrhometown);
            employee.setNationalityId(nationalityId);
        }

        // 籍贯
        if (StringUtils.isNotBlank(zhrhometown)) {
            Long nativePlaceId = getConfigId("native_place", zhrhometown);
            employee.setNativePlaceId(nativePlaceId);
        }

        // 手机号
        employee.setMobile(StringUtils.trimToNull(employeeData.getString("USRID")));

        // 政治面貌
        String politicsName = StringUtils.trimToNull(employeeData.getString("PCODE"));
        if (StringUtils.isNotBlank(politicsName)) {
            Long politicsId = getConfigId("politics", politicsName);
            employee.setPoliticsId(politicsId);
        }

        // 产业集团（二级）
        String orgtxGroup = StringUtils.trimToNull(employeeData.getString("ORGTX_GROUP"));
        if (StringUtils.isNotBlank(orgtxGroup)) {
            Long industrialGroupId = getConfigId("industrialGroup", orgtxGroup);
            employee.setIndustrialGroupId(industrialGroupId);
        }

        // 公司（三级）
        String bukrs = StringUtils.trimToNull(employeeData.getString("BUKRS"));
        if (StringUtils.isNotBlank(bukrs)) {
            Long companyId = getConfigId("company", bukrs);
            employee.setCompanyId(companyId);
        }

        // 一级部门
        String orgtx1 = StringUtils.trimToNull(employeeData.getString("ORGTX1"));
        if (StringUtils.isNotBlank(orgtx1)) {
            Long primaryDepartmentId = getConfigId("department", orgtx1);
            employee.setPrimaryDepartmentId(primaryDepartmentId);
        }

        // 二级部门
        String orgtx2 = StringUtils.trimToNull(employeeData.getString("ORGTX2"));
        if (StringUtils.isNotBlank(orgtx2)) {
            Long secondaryDepartmentId = getConfigId("department", orgtx2);
            employee.setSecondaryDepartmentId(secondaryDepartmentId);
        }

        // 三级部门
        String orgtx3 = StringUtils.trimToNull(employeeData.getString("ORGTX3"));
        if (StringUtils.isNotBlank(orgtx3)) {
            Long tertiaryDepartmentId = getConfigId("department", orgtx3);
            employee.setTertiaryDepartmentId(tertiaryDepartmentId);
        }

        // 职位描述
        employee.setJobName(StringUtils.trimToNull(employeeData.getString("PLSTX")));

        // 一级岗位目录
        String zyjgwml = StringUtils.trimToNull(employeeData.getString("ZYJGWML"));
        // 一级岗位目录文本
        String zyjgwwb = StringUtils.trimToNull(employeeData.getString("ZYJGWWB"));
        if (StringUtils.isNotBlank(zyjgwml) && StringUtils.isNotBlank(zyjgwwb)) {
            employee.setPrimaryLevelJobId(getConfigId("primaryLevelJob", zyjgwml, zyjgwwb));
        }

        // 二级岗位目录
        String zejgwml = StringUtils.trimToNull(employeeData.getString("ZEJGWML"));
        // 二级岗位目录文本
        String zejgwwb = StringUtils.trimToNull(employeeData.getString("ZEJGWWB"));
        if (StringUtils.isNotBlank(zejgwml) && StringUtils.isNotBlank(zejgwwb)) {
            employee.setSecondaryLevelJobId(getConfigId("secondaryLevelJob", zejgwml, zejgwwb));
        }

        // 三级岗位目录
        String zsjgwml = StringUtils.trimToNull(employeeData.getString("ZSJGWML"));
        // 三级岗位目录文本
        String zsjgwwb = StringUtils.trimToNull(employeeData.getString("ZSJGWWB"));
        if (StringUtils.isNotBlank(zsjgwml) && StringUtils.isNotBlank(zsjgwwb)) {
            employee.setTertiaryLevelJobId(getConfigId("tertiaryLevelJob", zsjgwml, zsjgwwb));
        }

        // 员工组
        String persg = StringUtils.trimToNull(employeeData.getString("PERSG"));
        if (StringUtils.isNotBlank(persg)) {
            employee.setEmployeeGroupId(getConfigId("employeeGroup", persg));
        }

        // 员工子组
        String persk = StringUtils.trimToNull(employeeData.getString("PERSK"));
        if (StringUtils.isNotBlank(persk)) {
            employee.setEmployeeSubgroupId(getConfigId("employeeSubgroup", persk));
        }

        // 入职日期
        String zrzrq = StringUtils.trimToNull(employeeData.getString("ZRZRQ"));
        employee.setEnterGroupDate(parseDate(zrzrq));

        // 参加工作日期
        String zgzrq = StringUtils.trimToNull(employeeData.getString("ZGZRQ"));
        employee.setStartWorkingDate(parseDate(zgzrq));

        // 连续工龄计算日期
        String zglrq = StringUtils.trimToNull(employeeData.getString("ZGLRQ"));
        employee.setEnterCompanyDate(parseDate(zglrq));

        // 获聘职称时间
        String zhrititled = StringUtils.trimToNull(employeeData.getString("ZHRITITLED"));
        employee.setHighestProfessionalDate(parseDate(zhrititled));

        // 最高获聘职称
        String zhrititleh = StringUtils.trimToNull(employeeData.getString("ZHRITITLEH"));
        if (StringUtils.isNotBlank(zhrititleh)) {
            employee.setHighestProfessionalTitleId(getConfigId("professionalTitle", zhrititleh));
        }

        // 获聘职称等级
        String zhrititlel = StringUtils.trimToNull(employeeData.getString("ZHRITITLEL"));
        if (StringUtils.isNotBlank(zhrititlel)) {
            employee.setSkillLevelId(getConfigId("skillLevel", zhrititlel));
        }

        // 最高学历
        String zhrjyxl = StringUtils.trimToNull(employeeData.getString("ZHRJYXL"));
        if (StringUtils.isNotBlank(zhrjyxl)) {
            employee.setHighestEducationId(getConfigId("education", zhrjyxl));
        }

        // 最高学位
        String zhrjyxwf = StringUtils.trimToNull(employeeData.getString("ZHRJYXWF"));
        if (StringUtils.isNotBlank(zhrjyxwf)) {
            employee.setHighestDegreeId(getConfigId("degree", zhrjyxwf));
        }

        // 毕业院校
        String zhrjybyyx = StringUtils.trimToNull(employeeData.getString("ZHRJYBYYX"));
        if (StringUtils.isNotBlank(zhrjybyyx)) {
            employee.setHighestDegreeSchoolId(getConfigId("school", zhrjybyyx));
        }

        // 最高学位专业
        String zhrjyzyf = StringUtils.trimToNull(employeeData.getString("ZHRJYZYF"));
        if (StringUtils.isNotBlank(zhrjyzyf)) {
            employee.setHighestDegreeMajorId(getConfigId("major", zhrjyzyf));
        }

        // 学习形式
        String zhrjyxs = StringUtils.trimToNull(employeeData.getString("ZHRJYXS"));
        if (StringUtils.isNotBlank(zhrjyxs)) {
            employee.setLearningFormId(getConfigId("learningForm", zhrjyxs));
        }

        // 是否在职
        String flag1 = StringUtils.trimToNull(employeeData.getString("FLAG1"));
        if (StringUtils.isNotBlank(flag1)) {
            employee.setStatus(Integer.parseInt(flag1));
        }

        return employee;
    }


    private Date parseDate(String dateString) {
        if (StringUtils.isBlank(dateString)) {
            return null;
        }
        try {
            return new SimpleDateFormat("yyyyMMdd").parse(dateString);
        } catch (ParseException e) {
            log.error("日期解析错误: {}", dateString, e);
            return null;
        }
    }

    private Long getConfigId(String handleName, String... params) {
        ConfigTableHandler handler = configTableHandlerFactory.getHandler(handleName);
        log.info("获取配置ID: {}", handleName);
        return handler.getOrCreateConfigId(params);
    }
}
